import  permision from "@/js_sdk/wa-permission/permission.js"


//检查权限
export const checkPromision = (key)=>{ //1=授权 0=未授权 -1=永久拒绝
	let androidKey = { //安卓授权的id
		location:'android.permission.ACCESS_FINE_LOCATION'
	}
	if(plus){
		return new Promise((resolve,reject)=>{
			checkOpenGPSServiceByAndroidIOS().then(async res=>{
				if(plus.os.name == "iOS"){
					resolve(permision.judgeIosPermission(key)?1:0)
				}else{
					let code = await permision.requestAndroidPermission(androidKey[key])
					resolve(code)
				}
			})
		})
	}
}

//打开权限
export const openPromisionSet = (key)=>{
	let config = {
		app:"壹建装",
		location:`使用您的位置权限`,
		camera:'使用您的摄像头权限',
		calendar:"使用您的日历权限",
		storage:"使用您的存储权限",
		record:"使用您的麦克风权限",
		contact:"获取您的联系人",
		sms:"获取您的短信",
		state:"使用您的手机识别权限",
		phone:"使用您的拨号权限",
		log:'获取您的拨号记录'
	}
	
	return new Promise((resolve,reject)=>{
		if(plus){
			uni.showModal({
				title:'授权申请',
				content:config.app+'申请'+config[key],
				success(e) {
					if(e.confirm){
						resolve(true)
						if(plus.os.name == "iOS"){
							permision.gotoAppPermissionSetting(key)
						}else{
							androidPermissionCheck(key)
						}
					}
					if(e.cancel){
						reject(true)
					}
				}
			})
		}
	})
}


const androidPermissions = {   //安卓权限
  camera: "android.permission.CAMERA", // 摄像头权限
  location: "android.permission.ACCESS_FINE_LOCATION", // 位置权限
  calendar: {
	read: "android.permission.READ_CALENDAR", // // 日历读取权限
	write: "android.permission.WRITE_CALENDAR", // // 日历写入权限
  },
  storage: {
	read: "android.permission.READ_EXTERNAL_STORAGE", // 存储读取权限
	write: "android.permission.WRITE_EXTERNAL_STORAGE", // 存储写入权限
  },
  record: "android.permission.RECORD_AUDIO", // 麦克风权限
  contact: {
	read: "android.permission.READ_CONTACTS", // 联系人读取权限
	write: "android.permission.WRITE_CONTACTS", // 联系人写入权限
  },
  sms: {
	read: "android.permission.READ_SMS", // 短信读取权限
	send: "android.permission.SEND_SMS", //短信发送权限
	receive: "android.permission.RECEIVE_SMS", // 短信接收权限
  },
  state: "android.permission.READ_PHONE_STATE", // 手机识别码权限
  phone: "android.permission.CALL_PHONE", // 拨打电话权限
  log: "android.permission.READ_CALL_LOG", // 通话记录权限
};

//获取权限id
const  getPermissionList =(permissionID)=>{
  const id = androidPermissions[permissionID];
  const list = [];
  if (typeof id == "string") {  //如果是字符串直接取出
	list[0] = id;
  } else {
	for (let key in id) { //是个对象，循环取出全部
	  list.push(id[key]);
	}
  }
  return list;
}

//安卓发起权限请求 0=暂时拒绝 1=通过 -1=永久拒绝
export  const androidPermissionCheck = (permissionID)=>{
	return new Promise((resolve,reject)=>{
		if(plus){ //是在app下
			let ids = getPermissionList(permissionID); //取出需要的权限id
			plus.android.requestPermissions(
			ids,
			(e)=>{  //成功回调
				let res = 0
				if(e.deniedAlways.length>0){	//权限被永久拒绝
					// 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
					console.log('Always Denied!!! '+e.deniedAlways.toString());
					res = -1
				}
				if(e.deniedPresent.length>0){	//权限被临时拒绝
					// 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
					console.log('Present Denied!!! '+e.deniedPresent.toString());
					res = 0
				}
				if(e.granted.length>0){	//权限被允许
					//调用依赖获取定位权限的代码
					console.log('Granted!!! '+e.granted.toString());
					res = 1
				}
				resolve({
					code:1,
					data:res
				})
			},
			(error)=>{ //失败回调
				reject({
				  code: 2,
				  data: `code:${error.code},msg:${error.message}!`,
				});
			}
			)
			
		}
	})
}

	//ios定位授权
export	const iosLocation = () =>{
	  if (plus) {  //app下运行
		let result = 0,
		  cLLocationManager = plus.ios.importClass("CLLocationManager"), //导入定位对象
		  authStatus = cLLocationManager.authorizationStatus(),
		  enable = cLLocationManager.locationServicesEnabled();
		if (enable && authStatus != 2) {
		  result = 1;
		} else {
		  result = 0;
		}
		plus.ios.deleteObject(cLLocationManager);
		return result;
	  } else {
		return null;
	  }
}

//检查是否开启定位
export const checkOpenGPSServiceByAndroidIOS = ()=> {
    let system = uni.getSystemInfoSync(); // 获取系统信息
	
	return new Promise((resolve,reject)=>{
		if (system.platform === 'android') { // 判断平台
		    var context = plus.android.importClass("android.content.Context");
		    var locationManager = plus.android.importClass("android.location.LocationManager");
		    var main = plus.android.runtimeMainActivity();
		    var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
		    if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
		        uni.showModal({
		            title: '提示',
		            content: '请打开定位服务功能',
		            success(e) {
						if(e.confirm){
							var Intent = plus.android.importClass('android.content.Intent');
							var Settings = plus.android.importClass('android.provider.Settings');
							var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							main.startActivity(intent); // 打开系统设置GPS服务页面
						}
		            }
		        });
		    }else{
				resolve(true)
			}
		} else if (system.platform === 'ios') {
		    var cllocationManger = plus.ios.import("CLLocationManager");
		    var enable = cllocationManger.locationServicesEnabled();
		    var status = cllocationManger.authorizationStatus();
		    plus.ios.deleteObject(cllocationManger);
		    if (enable && status != 2) {
				resolve(true)
		    } else {
		        uni.showModal({
		            title: '提示',
		            content: '请前往设置-隐私-定位服务打开定位服务功能',
		            success(e) {
						if(e.confirm){
							var UIApplication = plus.ios.import("UIApplication");
							var application2 = UIApplication.sharedApplication();
							var NSURL2 = plus.ios.import("NSURL");
							// var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
							// var setting2 = NSURL2.URLWithString("App-Prefs:root=LOCATION_SERVICES");
							 var setting2 = NSURL2.URLWithString("app-settings:");
							//var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
							// var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION_SERVICES");
							application2.openURL(setting2);
							plus.ios.deleteObject(setting2);
							plus.ios.deleteObject(NSURL2);
							plus.ios.deleteObject(application2);
						}
		            }
		        });
		    }
		}
	})
	
    
}
